using System;
using System.Linq;
using UnityEngine;
using QFramework;

namespace ProjectMyFarmAndShe
{
	public partial class ChallengePanel : ViewController,IController
	{
		private IChallengeSystem mSystem;

		private void Awake()
		{
			ChallengeItempTemplate.Hide();
			mSystem = this.GetSystem<IChallengeSystem>();
		}
		
		private void OnEnable()
		{
			CreateChallenge();
		}

		void Start()
		{
			// Code Here
			
		}

		void CreateChallenge()
		{
			foreach (var challengeSeries in mSystem.ChallengeDic.Values.Where(data=>data.OnUnLock()))
			{
				var data = challengeSeries.ChallengeDatas.FirstOrDefault(data =>
					!data.Finished && data.UnLockCondition(data));

				if (data != null)
				{
					var dataCache = data;
					
					ChallengeItempTemplate.InstantiateWithParent(Root)
						.Self(self =>
						{
							self.Init(dataCache);
							self.SubmitBtn.onClick.AddListener(() =>
							{
								dataCache.OnFinished();
								UpdateChallenge();
							});
						})
						.Show();
				}
			}
		}
		
		void UpdateChallenge()
		{
			Root.DestroyChildren();
			CreateChallenge();
		}

		private void OnDisable()
		{
			Root.DestroyChildren();
		}

		public IArchitecture GetArchitecture()
		{
			return Global.Interface;
		}
	}
}
